﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sofire.Data;

namespace SofireXSqlEntityGenerator.UI
{
    public partial class ResultDataForm : Form
    {
        public ResultDataForm()
        {
            InitializeComponent();
            this.Icon = Properties.Resources.SQL;
            this.StartPosition = FormStartPosition.CenterScreen;
            dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
        }

        private TableResult Data;
        public ResultDataForm(TableResult data):this()
        {
            this.Data = data;
            dataGridView1.DataSource = data.Value;
            dataGridView1.CellValueChanged += dataGridView1_CellValueChanged;
        }

        void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView1.CellValueChanged -= dataGridView1_CellValueChanged;
            this.Text = "查询结果 * ";
        }

        private void tsb_Save_Click(object sender, EventArgs e)
        {
            if(dataGridView1.DataSource == null
                || (dataGridView1.IsCurrentCellInEditMode && !dataGridView1.EndEdit())) return;
            this.Data.Update();
            if(this.IsSuccess(this.Data))
            {
                this.Text = "查询结果";
                dataGridView1.CellValueChanged += dataGridView1_CellValueChanged;
            }
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if(this.Data.IsChanged)
            {
                if(dataGridView1.IsCurrentCellInEditMode && !dataGridView1.EndEdit())
                {
                    e.Cancel = true;
                    return;
                }
                if(this.ShowYesNo("数据已发生变化，是否保存？"))
                {
                    this.Data.Update();
                    if(!this.IsSuccess(this.Data))
                    {
                        e.Cancel = true;
                        return;
                    }
                }
            }
            base.OnClosing(e);
        }
        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            this.Data.Dispose();
            this.Data = null;
            GC.Collect();
        }
    }
}
